package serv

import (
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func AdminUploadSaveCtrl(c *gin.Context) {
	f, _ := c.FormFile("file")

	uploadDir := "./public/uploads/" + time.Now().Format("2006/0102/")

	isDirExists, _ := PathExists(uploadDir)

	if !isDirExists {
		os.MkdirAll(uploadDir, 0777)
	}

	filePath := uploadDir + time.Now().Format("150405") + filepath.Ext(f.Filename)
	c.SaveUploadedFile(f, filePath)

	fileUrl := strings.ReplaceAll(filePath, "./public", "")

	c.JSON(200, map[string]any{
		"status": 200,
		"result": fileUrl,
	})
}

func AdminUploadEditorCtrl(c *gin.Context) {
	f, _ := c.FormFile("file")

	uploadDir := "./public/uploads/" + time.Now().Format("2006/0102/")

	isDirExists, _ := PathExists(uploadDir)

	if !isDirExists {
		os.MkdirAll(uploadDir, 0777)
	}

	filePath := uploadDir + time.Now().Format("150405") + filepath.Ext(f.Filename)
	c.SaveUploadedFile(f, filePath)

	fileUrl := strings.ReplaceAll(filePath, "./public", "")

	c.JSON(200, map[string]any{
		"status": 200,
		"data":   fileUrl,
	})
}
